package net.thread;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.zip.GZIPOutputStream;

public class GZipThread extends Thread
{
	@SuppressWarnings("rawtypes")
	private List pool;
	private static int fileCompressed = 0;
	public GZipThread(@SuppressWarnings("rawtypes") List pool)
	{
		this.pool = pool;
	}
	private static synchronized void incrementFilesCompressed()
	{
		fileCompressed++;
	}
	@Override
	public void run()
	{
		while(fileCompressed!=GZipAllFiles.getNumberOfFilesToBeCompressed())
		{
			File input = null;
			synchronized (pool)
			{
				while(pool.isEmpty())
				{
					if(fileCompressed == GZipAllFiles.getNumberOfFilesToBeCompressed())
					{
						System.out.println("Thread Ending!");
						return;
					}
					try
					{
						pool.wait();
					}
					catch (Exception e)
					{
					}
				}
				input = (File) pool.remove(pool.size()-1);
				incrementFilesCompressed();
			}
			if(!input.getName().endsWith(".gz"))
			{
				try
				{
					InputStream in = new  FileInputStream(input);
					in = new BufferedInputStream(in);
					
					File output = new File(input.getParent(),input.getName()+".gz");
					if(!output.exists())
					{
						OutputStream out = new FileOutputStream(output);
						out = new GZIPOutputStream(out);
						out = new BufferedOutputStream(out);
						int b;
						while((b=in.read())!=-1)
						{
							out.write(b);
						}
						out.flush();
						out.close();
						in.close();
					}
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
			}
		}
	}
}
